// 用户使用方式
// this.$api.文件名字() 返回promise
import qs from "qs";
import Settings from "../config/settings";
import Toast from "../utils/toast";
import store from "@/store";
import { logout } from "@/utils/user";

const files = require.context(".", false, /\.js$/);
const modules = {};

// 请求配置
const Config = {
  showLoading: true, // 是否展示loading, 默认展示
  header: {
    "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
    "client-type": 53, // 商家端(商户平台) 50  商户后台 52  商户后台助手小程序 53
  },
};

files.keys().forEach((key) => {
  if (key === "./index.js") return;
  const item = files(key).default;
  const PNAME = key.replace(/(\.\/|\.js)/g, "");
  //modules[PNAME] = item;
  modules[PNAME] = {};

  for (let i in item) {
    modules[PNAME][i] = (data, options = {}) => {
      // 配置合并
      options = {
        ...Config,
        ...options,
      };

      options.header = {
        ...Config.header,
        ...options.header,
        "shop-id": store.state?.account?.shopId, // 通过选择店铺获取
        "session-id": store.state?.account?.sessionId,
      };

      if (options.showLoading) {
        uni.showLoading({
          title: "加载中",
          mask: true,
        });
      }

      return new Promise((res, rej) => {
        let base_url = Settings.config.base_url;

        //#ifdef H5
        if (process.env.NODE_ENV === "development") {
          base_url = "/manageApi";
        }
        //#endif

        uni.request({
          url: base_url + item[i].url,
          data: qs.stringify(data),
          method: item[i].method,
          header: options.header,
          complete: (rs) => {
            if (options.showLoading) {
              uni.hideLoading();
              // 处理返回数据
              const { data } = rs;
              if (+data.error !== 0) {
                Toast(data.message);
                rej("获取sessionid接口错误错误码：" + data.error);
              } else {
                if (+data.error === 999) {
                  logout();
                }

                res(data);
              }
            }
          },
        });
      });
    };
  }
});

export default modules;
